<template>
  <!-- 模态框 -->
  <div class="modal">
    <!-- 遮罩层 -->
    <div class="mask" @click="changeIsShowLoginModal(false)"></div>
    <!-- 登录box -->
    <div class="loginBox">
      <div class="close" @click="changeIsShowLoginModal(false)"></div>
      <!-- 导航部分 -->
      <div class="nav">
        <!-- 手机号码登录 -->
        <a ref="#" :class="{ active: isShow }" @click="isShow = true"
          >手机号码登录</a
        >
        |
        <!-- 微信扫码登录 -->
        <a ref="#" :class="{ active: !isShow }" @click="showQR">微信扫码登录</a>
      </div>
      <!-- 内容部分 -->
      <div class="content">
        <div class="phoneCentent" v-show="isShow">
          <div class="row">
            <input
              type="text"
              placeholder="请输入手机号"
              class="ipt"
              v-model="phoneNumber"
            />
          </div>
          <div class="row">
            <slide-verify
              :l="42"
              :r="20"
              :w="362"
              :h="140"
              @success="onSuccess"
              @fail="onFail"
              @refresh="onRefresh"
              :style="{ width: '100%' }"
              class="slide-box"
              ref="slideBlock"
              :slider-text="msg"
              :imgs="arr"
              :accuracy="accuracy"
            ></slide-verify>
          </div>
          <div class="row">
            <input
              type="text"
              placeholder="请输入短信验证码"
              class="ipt"
              v-model="code"
            />
            <!-- <button class="btncode" @click="getCode">
              获取验证码{{ count }}
            </button> -->
            <!--  -->
            <button v-show="isShowCount" class="btncode" @click="getCode">
              获取验证码
            </button>
            <button v-show="!isShowCount" class="btncode">
              {{ count + "s" }}
            </button>
          </div>
          <div class="row">
            <button class="btnlogin" @click="submitFn">登录</button>
          </div>
        </div>
        <div class="qrcentent" v-show="!isShow" id="weixin"></div>
      </div>
    </div>
  </div>
</template>

<script>
import { validatePhoneNumber } from "@/utils/index";
import { mapMutations, mapState, mapActions } from "vuex";
import { sandSMSAPI, PhoneReginAPI, BindingAPI } from "@/request/api";
export default {
  data() {
    return {
      isShow: true,
      msg: "向右滑动",
      arr: [
        require("../assets/img/integral-01.9386d4bf.png"),
        require("../assets/img/integral-02.150d92a1.png"),
        require("../assets/img/integral-03.9870f3f1.png"),
        require("../assets/img/integral-04.afadcbdf.png"),
      ],
      accuracy: 10,
      // 输入手机号的表单的内容
      phoneNumber: "",
      // 倒计时时间
      count: 5,
      isShowCount: true,
      code: "",
    };
  },
  methods: {
    ...mapMutations({
      changeIsShowLoginModal: "showModal/changeIsShowLoginModal",
      changeIsLoginedShow: "loginStatus/changeIsLoginedShow",
    }),
    ...mapActions({
      asyncchangeIsShowToast: "showToast/asyncchangeIsShowToast",
      asyncchangeUserInfo: "userInfo/asyncchangeUserInfo",
    }),
    // 拼图成功
    onSuccess(times) {
      let ms = (times / 1000).toFixed(1);
      this.msg = "login success, 耗时 " + ms + "s";
    },
    // 拼图失败
    onFail() {
      this.onRefresh(); // 重新刷新拼图
    },
    // 拼图刷新
    onRefresh() {
      this.msg = "再试一次";
    },
    // 倒计时
    daojishi() {
      this.isShowCount = false;
      let timer = setInterval(() => {
        this.count--;
        if (this.count <= 0) {
          this.count = 5;
          // 停止 clear
          this.isShowCount = true;
          clearInterval(timer);
        }
      }, 1000);
    },
    // 判断手机号和滑块验证
    toVerify() {
      // 1.判断手机号码是否正确,不正确,提示
      // let reg =
      //   /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
      if (!validatePhoneNumber(this.phoneNumber)) {
        // return alert("请输入正确的手机号码");
        // this.changeIsShowToast({
        //   isShow: true,
        //   msg: "请输入正确的手机号码",
        //   type: "danger",
        // });
        // setTimeout(() => {
        //   this.changeIsShowToast({
        //     isShow: false,
        //   });
        // }, 1000);
        this.asyncchangeIsShowToast({
          isShow: true,
          msg: "请输入正确的手机号码",
          type: "info",
        });
        return;
      }
      // 2.滑块验证不正确 提示
      if (this.msg == "再试一次" || this.msg == "向右滑动") {
        // return alert("请移动滑块!");
        this.asyncchangeIsShowToast({
          isShow: true,
          msg: "请移动滑块",
          type: "info",
        });
        return;
      }
      return true;
    },
    // 获取验证码
    async getCode() {
      let flag = this.toVerify();
      // console.log(flag);
      if (!flag) return; //不通过时不往下执行
      // 3.获取验证码--60s倒计时功能
      let res = await sandSMSAPI({
        phone: this.phoneNumber,
      });
      // 获取验证码 -- 发送请求
      if (!res) return;
      // alert("发送成功");
      this.asyncchangeIsShowToast({
        isShow: true,
        msg: "发送成功",
        type: "success",
      });
      // 调用倒计时方法
      this.daojishi();
    },
    // 登录
    async submitFn() {
      // 1.手机号不正确提示
      // 2.滑块验证不正确提示
      if (!this.toVerify()) return;
      // 3.短信验证码不正确提示
      if (this.code.trim() == "") {
        // return alert("请输入短信验证码");
        this.asyncchangeIsShowToast({
          isShow: true,
          msg: "请输入短信验证码",
          type: "info",
        });
      }
      // 4.发起登录请求  两周情况  有uuid,发送手机绑定微信的请求 和 没有uuid,普通请求
      let uuid = localStorage.getItem("uuid");
      let res;
      if (uuid) {
        res = await BindingAPI({
          verifyCode: this.code,
          phone: this.phoneNumber,
          uuid,
        });
      } else {
        res = await PhoneReginAPI({
          verifyCode: this.code,
          phone: this.phoneNumber,
        });
      }
      if (!res) return;
      // 1.提示
      // alert("登录成功");
      this.asyncchangeIsShowToast({
        isShow: true,
        msg: "登录成功",
        type: "success",
      });
      // 2.存储token
      localStorage.setItem("x-auth-token", res["x-auth-token"]);
      // 3.关闭登录模态框
      this.changeIsShowLoginModal(false);

      // 4.tobar中登录状态的切换  (修改vuex中usLogined为true)
      this.changeIsLoginedShow(true);

      // 绑定1 清除code
      uuid && this.$router.push(this.$route.path);
      // 绑定1 删除uuid
      localStorage.removeItem("uuid");
      // 更新用户信息
      this.asyncchangeUserInfo();
    },
    // 微信二维码
    showQR() {
      this.isShow = false;
      //获取二维码 并展示
      // 申请微信登录二维码
      let _this = this;
      new WxLogin({
        id: "weixin",
        appid: "wx67cfaf9e3ad31a0d", // 这个appid要填死
        scope: "snsapi_login",
        // 扫码成功后重定向的接口
        redirect_uri: "https://sc.wolfcode.cn/cms/wechatUsers/shop/PC",
        // state填写编码后的url
        state: encodeURIComponent(
          window.btoa("http://127.0.0.1:8080" + _this.$route.path)
        ),
        // 调用样式文件
        href: "data:text/css;base64,LmltcG93ZXJCb3ggLnRpdGxlLA0KLmltcG93ZXJCb3ggLmluZm8gew0KICAgIGRpc3BsYXk6IG5vbmU7DQp9DQoNCi5pbXBvd2VyQm94IHFyY29kZSB7DQogICAgbWFyZ2luLXRvcDogMjBweDsNCn0=",
      });
    },
  },
};
</script>

<style lang="less" scoped>
.modal {
  width: 100%;
  height: 100%;
  position: fixed;
  left: 0;
  top: 0;
  .mask {
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
  }
  .loginBox {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    width: 555px;
    height: 423px;
    background: url("../assets/img/login-box-bg.png");
    .close {
      position: absolute;
      height: 22px;
      width: 22px;
      top: 15px;
      right: 65px;
      cursor: pointer;
      background: url("../assets/img/close.png");
    }
    .nav {
      padding-top: 40px;
      text-align: center;
      a {
        text-decoration: none;
        color: gray;
        &.active {
          color: black;
        }
      }
    }
    .content {
      width: 355px;
      height: 300px;
      margin: 30px auto 0;
      .row {
        display: flex;
        height: 50px;
        margin-bottom: 20px;
        .ipt {
          flex: 1;
          outline: none;
          text-indent: 1em;
        }
        .btncode {
          width: 86px;
          background-color: #063492;
          border: none;
          color: #fff;
          margin-left: 10px;
        }
        .btnlogin {
          width: 100%;
          background-color: #063492;
          color: #fff;
          border: none;
        }
      }
    }
    .qrcentent {
      text-align: center;
    }
  }
}

/deep/.slide-box {
  width: 100%;
  position: relative;
  box-sizing: border-box;
  canvas {
    position: absolute;
    left: 0;
    top: -120px;
    display: none;
    width: 100%;
    box-sizing: border-box;
  }
  .slide-verify-block {
    width: 85px;
    height: 136px;
  }
  .slide-verify-refresh-icon {
    top: -120px;
    display: none;
  }
  &:hover {
    canvas {
      display: block;
    }
    .slide-verify-refresh-icon {
      display: block;
    }
  }
}
</style>